import logging
import allure
import pytest
import requests
from help_api_master.api_keyword.api_key import ApiKey
from help_api_master.params.allParams import URL
# 逻辑层
class login():
    """登录接口测试类"""
    # 参数化测试数据
    def test_login(self, userdata):
        # 动态获取参数生成标题
        allure.dynamic.title(userdata['title'])
        # 初始化工具类
        apiKey = ApiKey()
        # 从测试数据中获取用户信息
        username = userdata['user']['username']  # 用户名
        password = userdata['user']['password']  # 密码
        expected_msg = userdata['msg']  # 预期响应消息
        test_title = userdata['title']  # 测试标题
        logging.info(f"\n开始执行测试用例：{test_title}")
        # 准备请求数据
        userInfo = {
            "username": username,
            "password": password
        }
        try:
            # 构建完整的 URL
            url = f"{URL}/api/user/login"
            print(f"\n请求 URL: {url}")
            # 使用封装的 ApiKey 类发送请求
            response = apiKey.post(
                url=url,
                json=userInfo,
                headers={"Content-Type": "application/json"}
            )
            with allure.step(f"发送登录请求，用户名：{username}，密码：{password}"):
                logging.info(f'登录接口请求响应信息:{response.text}')
                logging.info(f'响应状态码:{response.status_code}')
                logging.info(f'响应头:{response.headers}')
                # 获取响应结果（只调用一次 json()）
                result = response.json()
                # 获取响应消息
                msg = result.get('msg', '未找到msg字段')
                logging.info(f"响应消息：{msg}")
                logging.info(f"测试用例执行成功：{test_title}")
        except requests.RequestException as e:
            logging.info(f"请求异常：{str(e)}")
            pytest.fail(f"请求异常：{str(e)}")
        except AssertionError as e:
            logging.info(f"断言失败：{str(e)}")
            pytest.fail(f"断言失败：{str(e)}")
        except Exception as e:
            logging.info(f"测试执行异常：{str(e)}")
            pytest.fail(f"测试执行异常：{str(e)}")

